//
//  BookModel.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/20.
//

import UIKit
import HandyJSON
import RealmSwift

struct DiscoverModel: HandyJSON {
    var categoryList: [CategoryBookModel]?
}

struct CategoryBookModel: HandyJSON {
    var category: String?
    var bookList: [BookDetailModel]? // 列表
}

struct ChapterListModel: HandyJSON {
    var bookDetial: BookDetailModel?
    var list: [ChapterDetailModel]?
}

struct TagsModel: HandyJSON {
    var id: String?
    var label_name: String?
    var status: Int = 1 // 1-未选中 2-用户选中的
}

struct BookDetailModel: HandyJSON {
    var bookId: String? // 书Id
    var coverUrl: String? // 竖图
    var bannerUrl: String? // 横图
    var name: String? // 书名
    var bookName: String? // 书名
    var des: String? // 描述
    
    var userName: String? // 用户id
    var userId: String? // 用户id
    var avatar: String? // 用户头像
    
    var authorname: String? // 作者名
    var icon: String? // 作者头像
    var follow: Int = 0 // 作者关注数
    
    var status: Int = 0 // 完结状态 1：已经完结，2：更新中
    var stars: Int = 0 // 评分
    var readings: Int = 0 // 阅读量
    var num: Int = 0 // 阅读量
    var commentNum: Int = 0 // 评论数
    var favorite: Bool = false // 是否收藏
    var readingTime: String? // 最后观看记录时间
    var tags: [TagsModel]? // 书籍标签数组
    
    var chapters: Int = 0 // 总章节数
    var freepage: Int = 0 // 免费节数数
    var durChapterName: String? // 当前章节
    var durChapterId: Int = 0 // 当前章节Id
    var durContentIndex: Int = 1 // 当前内容页码
        
    var price: Int = 0 // 总价
//    var pricePerChapter: Int = 0 // 单章价格
    var disCount: Int = 0 // 单章免费比例 0-100
//    var disCountAll: Int = 0 //全本免费比例 0-100
        
    var giftDetial: [GiftModel]? // 收到的礼物
    var total: Int = 0 // 礼物总价
    var giftNum: Int = 0 // 礼物总数
    
    var pbChapterId: Int = 0 // 剪切板跳转章节Id
    
    var feeType: Int = 0 // 1：整本购买 2：按章节购买
    
    var isSel: Bool = false
    var showOpen: Bool = false
    var showDesAll: Bool = false
    var desClose: String = ""
    var desCloseH: CGFloat = 0
    var desOpen: String = ""
    var desOpenH: CGFloat = 0
    
    var otherDetailH: CGFloat = 0
    
    var recH: CGFloat = 0

    mutating func didFinishMapping() {
        if let des = des {
            if let arr = NSString.getLinesArrayWithfont(des, font: .wn_font(name: .bold, size: 12), andLableWidth: ScreenW-24) as? [NSString], arr.count > 0 {
                if arr.count > 2 {
                    showOpen = true
                    desClose = "\(arr[0])\(arr[1])"
                    desCloseH = wn_getTextH(textStr: "\(arr[0])\(arr[1])\n..MORE", font: .wn_font(name: .bold, size: 12), width: ScreenW-24, lineSpace: 0)
                    desOpen = des
                    desOpenH = wn_getTextH(textStr: "\(desOpen)\n Less", font: .wn_font(name: .bold, size: 12), width: ScreenW-24, lineSpace: 0)
                }else {
                    desCloseH = wn_getTextH(textStr: des, font: .wn_font(name: .bold, size: 12), width: ScreenW-24, lineSpace: 0)
                    showOpen = false
                }
            }
        }
        var nameH = 0.0
        if let na = name {
            nameH = wn_getTextH(textStr: na, font: .wn_font(name: .bold, size: 20), width: ScreenW-24, lineSpace: 0)

        }
        otherDetailH = 150+nameH
        recH = (ScreenW-36)*0.5*1.55 + 140
//        recH = (ScreenW-36)*0.5*1.55 + wn_getTextH(textStr: name ?? "", font: .wn_font(name: .bold, size: 14), width: (ScreenW-36)*0.5, lineSpace: 0) + wn_getTextH(textStr: des ?? "", font: .wn_font(name: .bold, size: 11), width: (ScreenW-36)*0.5, lineSpace: 0) + 32
    }
}

class ChapterDetailModel: NSObject, NSCoding, HandyJSON {
    var bookId = "" // 书Id
    var chapterName = "" // 章节名
    var chapterId = NSNumber(value: 0) // 章节Id
    
    var content = "" // 章节内容
    var chapterPrevId = NSNumber(value: -1) // 上一章节Id
    var chapterNextId = NSNumber(value: -1) // 下一章节Id
    var pageCount = NSNumber(value: 0) // 多少页
    var pageArr: [ChapterPageModel]?
    var fullContent = NSAttributedString() // 完整富文本内容
    var location = NSNumber(value: 0)
    
    var price = 0 // 章节价格
    var status = 0 // 章节解锁状态 /// 1-免费; 2-收费
    /// 分页总高 (上下滚动模式使用)
    var pageTotalHeight: CGFloat {
        var pageTotalHeight: CGFloat = 0
        if let arr = pageArr {
            for _ in arr {
                pageTotalHeight += RECORD_RECT.height
            }
        }
        return pageTotalHeight
    }
    
    func updateFont(_ isSave: Bool = true) {
        let titleStr = NSMutableAttributedString(string: "\(chapterName)\n\n", attributes: SNReadConfigure.shared.attributes(true))
        let contentStr = NSAttributedString(string: content, attributes: SNReadConfigure.shared.attributes(false))
        titleStr.append(contentStr)
        fullContent = titleStr
        pageArr = pageing(fullContent)
        pageCount = NSNumber(value: pageArr?.count ?? 0)
        if isSave {
            save()
        }
    }
    
    /// 获取指定页码富文本
    func contentAttributedString(page: Int) -> NSAttributedString {
        return pageArr?[page].showContent ?? NSAttributedString()
    }
    
    /// 获取指定页开始坐标
    func getLocationFirst(page: Int) -> NSNumber {
        return NSNumber(value: pageArr?[page].range.location ?? 0)
    }
    
    /// 获取存在指定坐标的页码
    func page(location: Int) -> NSNumber {
        let count = pageArr?.count ?? 0
        for i in 0..<count {
            let range = pageArr?[i].range
            if location < ((range?.location ?? 0) + (range?.length ?? 0)) {
                return NSNumber(value: i)
            }
        }
        return NSNumber(value: 0)
    }
    
    func save() {
        SNKeyedArchiver.archiver(bookId, chapterId.stringValue, object: self)
    }
    
    required override init() {
        
    }
    
    required init?(coder: NSCoder) {
        bookId = coder.decodeObject(forKey: "bookId") as? String ?? ""
        chapterName = coder.decodeObject(forKey: "chapterName") as? String ?? ""
        chapterId = coder.decodeObject(forKey: "chapterId") as? NSNumber ?? .init(value: 0)
        content = coder.decodeObject(forKey: "content") as? String ?? ""
        chapterPrevId = coder.decodeObject(forKey: "chapterPrevId") as? NSNumber ?? .init(value: 0)
        chapterNextId = coder.decodeObject(forKey: "chapterNextId") as? NSNumber ?? .init(value: 0)
        pageCount = coder.decodeObject(forKey: "pageCount") as? NSNumber ?? .init(value: 0)
        pageArr = coder.decodeObject(forKey: "pageArr") as? [ChapterPageModel]
        fullContent = coder.decodeObject(forKey: "fullContent") as? NSAttributedString ?? NSAttributedString()
        location = coder.decodeObject(forKey: "location") as? NSNumber ?? .init(value: 0)
    }
    
    func encode(with coder: NSCoder) {
        coder.encode(bookId, forKey: "bookId")
        coder.encode(chapterId, forKey: "chapterId")
        coder.encode(chapterPrevId, forKey: "chapterPrevId")
        coder.encode(chapterNextId, forKey: "chapterNextId")
        coder.encode(chapterName, forKey: "chapterName")
        coder.encode(content, forKey: "content")
        coder.encode(fullContent, forKey: "fullContent")
        coder.encode(pageCount, forKey: "pageCount")
        coder.encode(pageArr, forKey: "pageArr")
        coder.encode(location, forKey: "location")
    }
}

class BookRecordModel: NSObject, NSCoding, HandyJSON {
    var bookId = ""
    /// 阅读到的页码(上传阅读记录到服务器时传当前页面的 location 上去,从服务器拿回来 location 在转成页码。精准回到上次阅读位置)
    var page = NSNumber(value: 0)
    /// 当前记录的阅读章节
    var chapterModel: ChapterDetailModel?
    /// 当前记录的阅读章节当前页
    var pageModel: ChapterPageModel? { return chapterModel?.pageArr?[page.intValue] }
    /// 当前记录起始坐标
    var locationFirst: NSNumber? { return NSNumber(value: chapterModel?.pageArr?[page.intValue].range.location ?? 0) }
    /// 当前记录页码富文本
    var contentAttributedString: NSAttributedString? { return chapterModel?.pageArr?[page.intValue].showContent }
    
    /// 当前记录切到上一页
    func previousPage() { page = NSNumber(value: max(page.intValue-1, 0)) }
    /// 当前记录切到下一页
    func nextPage() { page = NSNumber(value: min(page.intValue + 1, (chapterModel?.pageCount.intValue ?? 0) - 1)) }
        
    /// 当前记录切到第一页
    func firstPage() { page = NSNumber(value: 0) }
    /// 当前记录切到最后一页
    func lastPage() { page = NSNumber(value: (chapterModel?.pageCount.intValue ?? 0)-1) }
    
    /// 修改阅读记录为指定章节位置
    func modify(model: ChapterDetailModel?, toPage: Int) {
        chapterModel = model
        page = NSNumber(value: toPage)
        save()
    }
    /// 修改阅读记录为指定章节位置
    func modify(chapterId: NSNumber, location: Int) {
        if SNKeyedArchiver.isExist(bookId, chapterId.stringValue) {
            chapterModel = SNKeyedArchiver.unarchiver(bookId, chapterId.stringValue) as? ChapterDetailModel
            page = chapterModel?.page(location: location) ?? NSNumber(value: 0)
            save()
        }
    }
    /// 修改阅读记录为指定章节页码
    func modify(chapterId: NSNumber, toPage: Int) {
        if SNKeyedArchiver.isExist(bookId, chapterId.stringValue) {
            chapterModel = SNKeyedArchiver.unarchiver(bookId, chapterId.stringValue) as? ChapterDetailModel
            if (toPage == -1) {
                lastPage()
            }else {
                page = NSNumber(value: toPage)
            }
            save()
        }
    }
    /// 更新字体
    func updateFont() {
        if chapterModel != nil {
            chapterModel?.updateFont()
            chapterModel?.location = NSNumber(value: READ_RECORD_CURRENT_CHAPTER_LOCATION)
            page = chapterModel?.page(location: READ_RECORD_CURRENT_CHAPTER_LOCATION) ?? 0
            save()
        }
    }
    
    func save() {
        SNKeyedArchiver.archiver(bookId, READ_RECORD, object: self)
    }
    
    required override init() {
        
    }
    
    required init?(coder: NSCoder) {
        bookId = coder.decodeObject(forKey: "bookId") as? String ?? ""
        page = coder.decodeObject(forKey: "page") as? NSNumber ?? .init(value: 0)
        chapterModel = coder.decodeObject(forKey: "chapterModel") as? ChapterDetailModel
    }
    
    func encode(with coder: NSCoder) {
        coder.encode(bookId, forKey: "bookId")
        coder.encode(chapterModel, forKey: "chapterModel")
        coder.encode(page, forKey: "page")
    }
}

class ChapterPageModel: NSObject, NSCoding, HandyJSON {

    /// 当前页内容
    var content = NSAttributedString()
    /// 滚动模式使用
    var contentH = NSNumber(value: 0)
    /// 当前页序号
    var page = NSNumber(value: 0)
    /// 当前页范围
    var range = NSRange.init(location: 0, length: 0)
    /// 获取显示内容
    var showContent: NSAttributedString {
        let showC = NSMutableAttributedString(attributedString: content)
        showC.addAttributes([.foregroundColor : SNReadConfigure.shared.textColor], range: NSMakeRange(0, content.length))
        return showC
    }
    
    required override init() {

    }

    func encode(with coder: NSCoder) {
        coder.encode(content, forKey: "content")
        coder.encode(contentH, forKey: "contentH")
        coder.encode(range, forKey: "range")
        coder.encode(page, forKey: "page")
    }
    
    required init?(coder: NSCoder) {
        content = coder.decodeObject(forKey: "content") as? NSAttributedString ?? NSAttributedString()
        contentH = coder.decodeObject(forKey: "contentH") as? NSNumber ?? .init(value: 0)
        range = coder.decodeObject(forKey: "range") as? NSRange ?? .init(location: 0, length: 0)
        page = coder.decodeObject(forKey: "page") as? NSNumber ?? .init(value: 0)
    }
}
